package com.poizon.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.poizon.config.SystemConfig;

/**
 * @ClassName SmsUtils
 * @Author NoCheng
 * @Date 2022/1/2 10:39
 * @Description:TODO 短信验证码工具
 */

public class SmsUtils {
    private static Client client;

    static {
        //AccessKeyId 阿里云账号的key AccessKeySecret 阿里云账号的密钥
        Config config = new Config()
                .setAccessKeyId(SystemConfig.ALI_KEY)
                .setAccessKeySecret(SystemConfig.ALI_SEC);
        //endpoint 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            client = new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送验证码
     *
     * @param code    验证码
     * @param phone   手机号
     * @param temCode 模板code
     */
    public static boolean sendCode(String temCode, String phone, int code) {
        //1.准备请求参数
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("来自邢朋辉的短信")
                .setTemplateCode(temCode)
                .setTemplateParam("{\"code\":" + code + "}");
        try {
            //2.发送短信，获取响应结果
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            //3.返回结果
            return response.getBody().code.equals("OK");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
